package com.qinggeng.project.system.controller;

import com.qinggeng.common.enums.CommonEnum;
import com.qinggeng.common.utils.QrcodeUtil;
import com.qinggeng.common.utils.SecurityUtils;
import com.qinggeng.common.utils.ServletUtils;
import com.qinggeng.common.utils.poi.ExcelUtil;
import com.qinggeng.framework.aspectj.lang.annotation.Log;
import com.qinggeng.framework.aspectj.lang.enums.BusinessType;
import com.qinggeng.framework.interceptor.annotation.RepeatSubmit;
import com.qinggeng.framework.security.LoginUser;
import com.qinggeng.framework.security.service.TokenService;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.framework.web.page.TableDataInfo;
import com.qinggeng.project.system.domain.Shop;
import com.qinggeng.project.system.service.IShopService;
import com.qinggeng.project.tool.file.domain.SysFile;
import com.qinggeng.project.tool.file.service.ISysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 商户信息Controller
 *
 * @author qinggeng
 * @date 2020-05-29
 */
@RestController
@RequestMapping("/system/shop")
public class ShopController extends BaseController {
    @Autowired
    private IShopService shopService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysFileService sysFileService;


    /**
     * 查询商户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:shop:list')")
    @GetMapping("/list")
    public TableDataInfo list(Shop shop) throws IOException {
        startPage();
        shop.setDelFalg(CommonEnum.STATUS_10.getValue());
        List<Shop> list = shopService.selectShopList(shop);
        for (Shop shopInfo:list){
            ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
            ImageIO.write(QrcodeUtil.createQRCode("http://shoph5.gsd520.com?id="+shopInfo.getId()), "png", baos);//写入流中
            byte[] bytes = baos.toByteArray();//转换成字节
            BASE64Encoder encoder = new BASE64Encoder();
            String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
            png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
            shopInfo.setQrcodeImg(png_base64);
        }
        return getDataTable(list);
    }

    /**
     * 导出商户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:shop:export')")
    @Log(title = "商户信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Shop shop) {
        List<Shop> list = shopService.selectShopList(shop);
        ExcelUtil<Shop> util = new ExcelUtil<Shop>(Shop.class);
        return util.exportExcel(list, "shop");
    }

    /**
     * 获取商户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:shop:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(shopService.selectShopById(id));
    }

    /**
     * 新增商户信息
     */
    @PreAuthorize("@ss.hasPermi('system:shop:add')")
    @Log(title = "商户信息", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit //防止重复提交
    public AjaxResult add(@RequestBody Shop shop) {
        return toAjax(shopService.insertShop(shop));
    }

    /**
     * 修改商户信息
     */
    @PreAuthorize("@ss.hasPermi('system:shop:edit')")
    @Log(title = "商户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@RequestBody Shop shop) {
        return toAjax(shopService.updateShop(shop));
    }

    /**
     * 删除商户信息
     */
    @PreAuthorize("@ss.hasPermi('system:shop:remove')")
    @Log(title = "商户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(shopService.deleteShopByIds(ids));
    }

    //获取店铺详情
    @GetMapping("/getShopInfo")
    @ResponseBody
    public AjaxResult getShopInfo() {
        Long shopId = SecurityUtils.getShopId();
        if (shopId == null) {
            return AjaxResult.error("无店铺信息！");
        }
        Shop shop = shopService.selectShopById(shopId);
        return AjaxResult.success(shop);
    }

    /**
     * 头像上传
     */
    @Log(title = "商户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

            SysFile sysFile = sysFileService.upload(file,false);
            if (shopService.updateShopLog(loginUser.getUser().getUserId(), sysFile.getPath())) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", sysFile.getPath());
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }
}
